#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "canswerform.h"
#include <QPushButton>
#include <QFileDialog>
#include <QMessageBox>
#include <QTextDocumentFragment>
#include <QSizeF>
#include <QColorDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //Инициализация указателей
    this->testModel = 0;
    this->curTextEdit = 0;
    this->prevCurTextEdit = 0;
    this->fontSizeComboBox = 0;
    this->fontComboBox = 0;
    this->paginationForm = 0;
    this->grpAlign = 0;
    this->grpQuest = 0;
    this->grpFormating = 0;
    this->aboutDlg = 0;
    this->pageSetupDlg = 0;
    this->pageSettings = 0;
    this->appSettingsDlg = new CAppSettingsDlg(this);

    ui->setupUi(this);
    this->showMaximized();

    ui->questTextEdit->setEnabled(false);
    ui->paginationAction->setEnabled(false);
    ui->actionAddImage->setEnabled(false);

//    connect (ui->questTextEdit, SIGNAL(doubleClick(CTextEdit*)), this, SLOT(dblClickOnTextEdit(CTextEdit*)));
//    connect (ui->commentTextEdit, SIGNAL(doubleClick(CTextEdit*)), this, SLOT(dblClickOnTextEdit(CTextEdit*)));

    makeInterface();
    createAction();
    createStandardToolBar();
    createFormattingToolBar();
    restoreAppSettings();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setWidgets(QWidget* oldWidget, QWidget* newWidget)
{
    if (this->curTextEdit != NULL)
	this->prevCurTextEdit = this->curTextEdit;

    if (newWidget)
    {
	if (QVariant(newWidget->metaObject()->className()).toString() == "CTextEdit")
	{
	    this->curTextEdit = qobject_cast<CTextEdit*>(newWidget);
	}
	else
	{
	    ui->actionDelAnswer->setEnabled(false);
	    this->grpAlign->setEnabled(false);
	    this->grpFormating->setEnabled(false);
	    ui->actionFontColor->setEnabled(false);
	    return;
	}
    }

    if (!this->curTextEdit)
    {
	return;
    }
    else
    {
	if (this->curTextEdit->objectName()=="questTextEdit" || this->curTextEdit->objectName()=="commentTextEdit")
	    ui->actionDelAnswer->setEnabled(false);

	CTextEdit *w = qobject_cast<CTextEdit*>(oldWidget);
	if (w)
	{
	    disconnect(w, SIGNAL(currentCharFormatChanged(const QTextCharFormat &)), this, SLOT(currentCharFormatChanged(const QTextCharFormat &)));
	    disconnect (w, SIGNAL(doubleClick(CTextEdit*)), this, SLOT(dblClickOnTextEdit(CTextEdit*)));
	}
	connect(this->curTextEdit, SIGNAL(currentCharFormatChanged(const QTextCharFormat &)), this, SLOT(currentCharFormatChanged(const QTextCharFormat &)));
	connect (this->curTextEdit, SIGNAL(doubleClick(CTextEdit*)), this, SLOT(dblClickOnTextEdit(CTextEdit*)));
	this->currentCharFormatChanged(this->curTextEdit->currentCharFormat());
	//Interface activate
	this->addPictBtn->setEnabled(true);
	this->grpAlign->setEnabled(true);
	this->grpFormating->setEnabled(true);
	ui->actionFontColor->setEnabled(true);
    }
}

void MainWindow::createAction()
{
    //Группа действий для выравнивания текста
    grpAlign = new QActionGroup(this);
    grpAlign->setEnabled(false);
    connect(grpAlign, SIGNAL(triggered(QAction *)), this, SLOT(makeTextAlign(QAction *)));

    ui->actionCenter->setActionGroup(grpAlign);
    ui->actionLeft->setActionGroup(grpAlign);
    ui->actionRight->setActionGroup(grpAlign);
    ui->actionJustify->setActionGroup(grpAlign);

    //Группа действий для установки начертания текста
    this->grpFormating = new QActionGroup(this);
    this->grpFormating->setEnabled(false);
    this->grpFormating->setExclusive(false);

    ui->actionBold->setActionGroup(grpFormating);
    ui->actionUnderline->setActionGroup(grpFormating);
    ui->actionItalic->setActionGroup(grpFormating);

    ui->actionFontColor->setActionGroup(grpFormating);

    //Для печати
    this->grpPrint = new QActionGroup(this);
    this->grpPrint->setEnabled(false);
    ui->printKeysAction->setActionGroup(grpPrint);
    ui->printCommentAction->setActionGroup(grpPrint);
    ui->printTestAction->setActionGroup(grpPrint);
    ui->actionPreview->setActionGroup(grpPrint);
    ui->actionPageSetup->setActionGroup(grpPrint);
}

void MainWindow::makeInterface()
{
    ui->centralWidget->setVisible(false);

    QVBoxLayout *leftVbl = new QVBoxLayout(this);
    leftVbl->addWidget(ui->questListView);

    rightVbl = new QVBoxLayout(this);
    rightVbl->addWidget(ui->questTextEdit, 1);
    rightVbl->setSpacing(20);
    testsWidget = new QWidget(this);
    testsVbl = new QVBoxLayout(this);

    testsWidget->setLayout(testsVbl);
    ui->scrollArea->setWidget(testsWidget);

    rightVbl->addWidget(ui->scrollArea,8);
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->addLayout(leftVbl);
    mainLayout->addLayout(rightVbl);
    ui->centralWidget->setLayout(mainLayout);

    rightVbl->addWidget(ui->commentTextEdit, 1);
    rightVbl->setSpacing(20);
}

void MainWindow::createStandardToolBar()
{
    //Add buttons into toolbar
    newBtn = new QToolButton(this);
    newBtn->setDefaultAction(ui->newAction);
    ui->mainToolBar->addWidget(newBtn);
    connect(ui->newAction,SIGNAL(triggered()), this, SLOT(init()));

    loadBtn = new QToolButton(this);
    loadBtn->setDefaultAction(ui->openAction);
    ui->mainToolBar->addWidget(loadBtn);
    connect(ui->newAction,SIGNAL(triggered()), this, SLOT(init()));

    saveBtn = new QToolButton(this);
    saveBtn->setDefaultAction(ui->saveAction);
    ui->mainToolBar->addWidget(saveBtn);

    printBtn = new QToolButton(this);
    printBtn->setDefaultAction(ui->printTestAction);
    ui->mainToolBar->addWidget(printBtn);

    ui->mainToolBar->addSeparator();

    addQuest = new QToolButton;
    addQuest->setDefaultAction(ui->actionAddQuestion);
    ui->mainToolBar->addWidget(addQuest);

    delQuest = new QToolButton(this);
    delQuest->setDefaultAction(ui->actionDelQuestion);
    ui->mainToolBar->addWidget(delQuest);

    ui->mainToolBar->addSeparator();

    saveQuestBtn = new QToolButton(this);
    saveQuestBtn->setDefaultAction(ui->actionSaveQuestion);
    ui->mainToolBar->addWidget(saveQuestBtn);

    addAnswerBtn = new QToolButton(this);
    addAnswerBtn->setDefaultAction(ui->actionAddAnswer);
    ui->mainToolBar->addWidget(addAnswerBtn);

    delAnswerBtn = new QToolButton(this);
    delAnswerBtn->setDefaultAction(ui->actionDelAnswer);
    ui->mainToolBar->addWidget(delAnswerBtn);

    addPictBtn = new QToolButton(this);
    addPictBtn->setDefaultAction(ui->actionAddImage);
    ui->mainToolBar->addWidget(addPictBtn);
}

void MainWindow::createFormattingToolBar()
{
    fontComboBox = new QFontComboBox(this);
    fontComboBox->setCurrentFont(QApplication::font());
    qDebug()<<QApplication::font();
    connect(fontComboBox, SIGNAL(activated(const QString &)), this, SLOT(setTextFamily(const QString &)));
    ui->formattingToolBar->addWidget(fontComboBox);

    fontSizeComboBox = new QComboBox(this);
    fontSizeComboBox->clear();
    for (int i = 8; i <= 60; i+=2)
	fontSizeComboBox->addItem(QString("%1").arg(i));
    connect(fontSizeComboBox, SIGNAL(activated(const QString &)), this, SLOT(setTextSize(const QString &)));
    fontSizeComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    fontSizeComboBox->setEditable(false);
    fontSizeComboBox->setCurrentIndex(2);
    ui->formattingToolBar->addWidget(fontSizeComboBox);

    ui->formattingToolBar->addSeparator();

    boldBtn = new QToolButton(this);
    boldBtn->setDefaultAction(ui->actionBold);
    ui->formattingToolBar->addWidget(boldBtn);

    italicBtn = new QToolButton;
    italicBtn->setDefaultAction(ui->actionItalic);
    ui->formattingToolBar->addWidget(italicBtn);

    underBtn = new QToolButton(this);
    underBtn->setDefaultAction(ui->actionUnderline);
    ui->formattingToolBar->addWidget(underBtn);

    ui->formattingToolBar->addSeparator();

    leftAlignBtn  = new QToolButton(this);
    leftAlignBtn->setDefaultAction(ui->actionLeft);
    ui->formattingToolBar->addWidget(leftAlignBtn);

    centerAlignBtn = new QToolButton(this);
    centerAlignBtn->setDefaultAction(ui->actionCenter);
    ui->formattingToolBar->addWidget(centerAlignBtn);

    rightAlignBtn  = new QToolButton(this);
    rightAlignBtn->setDefaultAction(ui->actionRight);
    ui->formattingToolBar->addWidget(rightAlignBtn);

    jusifyAlignBtn  = new QToolButton(this);
    jusifyAlignBtn->setDefaultAction(ui->actionJustify);
    ui->formattingToolBar->addWidget(jusifyAlignBtn);

    ui->formattingToolBar->addSeparator();

    QColor black("black");
    colorChanged(black);
    colorBtn = new QToolButton(this);
    colorBtn->setDefaultAction(ui->actionFontColor);
    ui->formattingToolBar->addWidget(colorBtn);
}

void MainWindow::init()
{
    ui->actionLeft->setChecked(true);
    ui->actionRight->setChecked(false);
    ui->actionJustify->setChecked(false);
    ui->actionCenter->setChecked(false);

    ui->actionBold->setChecked(false);
    ui->actionItalic->setChecked(false);
    ui->actionUnderline->setChecked(false);

    this->fontComboBox->setCurrentFont(QApplication::font());
    this->fontSizeComboBox->setCurrentIndex(2);

}

void MainWindow::restoreAppSettings()
{
    if (this->appSettingsDlg)
    {
	QSettings settings("Test2Print", "Test2Print");
	int d = settings.value("defaultAnswersCount", 4).toInt();
	appSettingsDlg->setDefaultAnswersCount(d);
    }
}

void MainWindow::initModel()
{
    ui->questListView->setModel(testModel);
    selectionModel = ui->questListView->selectionModel();
    connect(selectionModel, SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(showSelectedItem( const QItemSelection &, const QItemSelection &)));
    connect(this, SIGNAL(answerAdded(int,int)), testModel, SLOT(addEmptyAnswer(int,int)));
    ui->actionAddQuestion->setEnabled(true);
    ui->actionDelQuestion->setEnabled(true);
}

int MainWindow::mbContinue(QString &text, QString title)
{
    return QMessageBox::question(this, title, text,
				  QMessageBox::Yes | QMessageBox::Default,
				  QMessageBox::No,
				  QMessageBox::Cancel | QMessageBox::Escape);
}

void MainWindow::setTitle(QString &text)
{
    this->setWindowTitle(text);
}

void MainWindow::deleteAnswerForms()
{
    int tmp=answerList.count();
    for (int i=0; i<tmp; i++)
    {
	CAnswerForm *al;
	al = answerList.last();
	disconnect(al, SIGNAL(answerClicked(CAnswerForm*)), this, SLOT(answerClicked(CAnswerForm*)));
	answerList.remove(answerList.count()-1);
	delete al;
    }
}

bool MainWindow::openFile(QString t2pFile)
{
    if (ui->saveAction->isEnabled())
    {
	QString text = tr("Сохранить изменения и открыть другой файл?");
	int r = mbContinue(text);
	switch (r)
	{
	case QMessageBox::Cancel:
            return false;
	case QMessageBox::Yes:
	    this->saveFile();
	    break;
	}
    }
    if (t2pFile == "")
	this->t2pFile = QFileDialog::getOpenFileName(this, tr("Открыть файл..."), "", tr("Файлы тестов (*.t2p)"));
    if (this->t2pFile == "") return false;
    testModel = new CTestModel(this->t2pFile, this);
    QString title = tr("Test2Print - ") + this->t2pFile;
    //QString dir = testModel->getTmpDir();
    //ui->questTextEdit->setCurrentDir(dir);
    //ui->commentTextEdit->setCurrentDir(dir);
    this->setTitle(title);
    if (!ui->centralWidget->isVisible()) ui->centralWidget->setVisible(true);
    this->initModel();
    ui->paginationAction->setEnabled(true);
    ui->actionAddImage->setEnabled(true);
    return true;
}

void MainWindow::saveFile()
{
    ui->saveAction->setEnabled(false);
//    ui->saveAsAction->setEnabled(false);
    if (this->saveQuestBtn->isEnabled())
	this->saveItem();
    if (t2pFile == "")
    {
	t2pFile = QFileDialog::getSaveFileName(this, tr("Сохранить файл"), "", tr("Файлы тестов (*.t2p)"));
	QString title = tr("Test2Print - ") + t2pFile;
	this->setTitle(title);
    }
    if (!testModel->writeTestList(t2pFile))
    {
	QMessageBox box(this);
	box.setWindowTitle( tr("Test2Print") );
	box.setText(tr("Ошибка записи в файл"));
	box.setIcon( QMessageBox::Critical );
	box.exec();
    };
}

void MainWindow::saveAsFile()
{
    QString tmp = QFileDialog::getSaveFileName(this, tr("Сохранить файл"), "", tr("Файлы тестов (*.t2p)"));
    if (tmp != "")
    {
        t2pFile = tmp;
    }
    else return;
    this->saveFile();
    this->openFile(tmp);
    ui->saveAction->setEnabled(false);
//    ui->saveAsAction->setEnabled(false);
}

void MainWindow::saveItem()
{
    on_actionSaveQuestion_triggered();
}

void MainWindow::addPict()
{

}

bool  MainWindow::imageExtension( QString fileName)
{
    bool ok = false;
    QString na;
    na = fileName.toLower();
    if (na.endsWith(".png") or na.endsWith(".jpeg") or na.endsWith(".jpg") or na.endsWith(".gif"))
    {
	ok = true;
    }
    return ok;
}

void MainWindow::showSelectedItem( const QItemSelection & selected, const QItemSelection & deselected )
{
    QModelIndexList list = selected.indexes();
    if (this->saveQuestBtn->isEnabled())
    {
	QString text = tr("Сохранить изменения и перейти к выбранному вопросу?");
	int r = mbContinue(text);
	switch (r)
	{
	case QMessageBox::Cancel:
	    selectionModel->blockSignals(true);
	    selectionModel->clearSelection();
	    selectionModel->setCurrentIndex(deselected.indexes().at(0),QItemSelectionModel::Select);
	    selectionModel->blockSignals(false);
	    return;
	case QMessageBox::Yes:
	    selectionModel->blockSignals(true);
	    selectionModel->clearSelection();
	    selectionModel->setCurrentIndex(deselected.indexes().at(0),QItemSelectionModel::Select);
	    this->saveItem();
	    selectionModel->clearSelection();
	    selectionModel->setCurrentIndex(selected.indexes().at(0),QItemSelectionModel::Select);
	    selectionModel->blockSignals(false);
	    break;
	}
    }

    this->ui->actionDelAnswer->setEnabled(false);
    if (list.isEmpty())
    {
	ui->actionDelQuestion->setEnabled(false);
        return;
    }

    ui->actionDelQuestion->setEnabled(true);
    QModelIndex item;
    item = list[0];
    int row = item.row();
    if (list.count() == 1)
    {
	//Отображаем текст вопроса
	ui->questTextEdit->setText((testModel->data(testModel->index(row, 1, item)).toString()));
	//Отображаем текст комментария
	ui->commentTextEdit->setText((testModel->data(testModel->index(row, 2, item)).toString()));
	//Создание ответов
	this->deleteAnswerForms();

	int tmp=((testModel->columnCount(list[0])-2)/ANSWCOLUMN);
        /* 2 - заголовок вопроса из модели + текст вопроса из файла
        *  3 - ответ содерижт текст ответа, верный ответ, коммент
        */
        for (int i=0; i<tmp; i++)
        {
            CAnswerForm *al;
            al = new CAnswerForm(this);
            answerList.append(al);
            testsVbl->insertWidget(i, answerList.last());
            answerList.last()->show();
            connect(answerList.last(), SIGNAL(rightAnswerChecked()), this, SLOT(rightAnswerChecked()));
            connect(answerList.last(), SIGNAL(answerChanged()), this, SLOT(answerChanged()));
            connect(answerList.last(), SIGNAL(answerClicked(CAnswerForm*)), this, SLOT(answerClicked(CAnswerForm*)));
        }
    }

    //Обновляем все поля с ответами
    for (int i=0; i<answerList.count(); i++)
    {
        answerList[i]->reset();
	answerList[i]->setAnswer((testModel->data(testModel->index(row, i*ANSWCOLUMN+3,item)).toString()));
	answerList[i]->setRightAnswer((testModel->data(testModel->index(row, i*ANSWCOLUMN+4,item)).toBool()));
    }
    ui->actionSaveQuestion->setEnabled(false);
    ui->actionAddAnswer->setEnabled(true);
    ui->questTextEdit->setEnabled(true);
    countAddAnswer=0;

}

void MainWindow::rightAnswerChecked()
{
    ui->actionSaveQuestion->setEnabled(true);
    ui->saveAction->setEnabled(true);
    ui->saveAsAction->setEnabled(true);
}

void MainWindow::answerChanged()
{
    ui->actionSaveQuestion->setEnabled(true);
    ui->saveAction->setEnabled(true);
    ui->saveAsAction->setEnabled(true);
}

void MainWindow::commentChanged()
{
    ui->actionSaveQuestion->setEnabled(true);
    ui->saveAction->setEnabled(true);
    ui->saveAsAction->setEnabled(true);
}

void MainWindow::answerClicked(CAnswerForm *answerForm)
{
    //запоминаем адрес answerForm'а,
    //textEdit или checkBox которого получил фокус
    this->curAnswerForm = answerForm;
    this->ui->actionDelAnswer->setEnabled(true);
}

void MainWindow::on_questTextEdit_textChanged()
{
    ui->actionSaveQuestion->setEnabled(true);
    ui->saveAction->setEnabled(true);
    ui->saveAsAction->setEnabled(true);
}

void MainWindow::on_commentTextEdit_textChanged()
{
    ui->actionSaveQuestion->setEnabled(true);
    ui->saveAction->setEnabled(true);
    ui->saveAsAction->setEnabled(true);
}

void MainWindow::on_saveAsAction_activated()
{
    this->saveAsFile();
}

void MainWindow::on_printKeysAction_triggered()
{
    CPrintTest *print = 0;
    print = new CPrintTest(this);
    print->printKeys(testModel->getTest());
    if (print != 0)
	delete print;
}


void MainWindow::on_printCommentAction_triggered()
{
    CPrintTest *print = 0;
    print = new CPrintTest(this);
    print->printComment(testModel->getTest());
    if (print != 0)
	delete print;
}

void MainWindow::currentCharFormatChanged(const QTextCharFormat &format)
{
    fontChanged(format.font());
    if (this->curTextEdit)
    {
	makeAlignmentChanged(this->curTextEdit->alignment());
    }
    colorChanged(format.foreground().color());
}

void MainWindow::makeAlignmentChanged(Qt::Alignment a)
{
    if (a & Qt::AlignLeft)
	ui->actionLeft->setChecked(true);
    else if (a & Qt::AlignHCenter)
	ui->actionCenter->setChecked(true);
    else if (a & Qt::AlignRight)
	ui->actionRight->setChecked(true);
    else if (a & Qt::AlignJustify)
	ui->actionJustify->setChecked(true);
}

void MainWindow::makeTextAlign(QAction *a)
{
    if (a == ui->actionLeft)
	this->curTextEdit->setAlignment(Qt::AlignLeft);
    else if (a == ui->actionCenter)
	this->curTextEdit->setAlignment(Qt::AlignHCenter);
    else if (a == ui->actionRight)
	this->curTextEdit->setAlignment(Qt::AlignRight);
    else if (a == ui->actionJustify)
	this->curTextEdit->setAlignment(Qt::AlignJustify);
}


void MainWindow::fontChanged(const QFont &f)
{
    ui->actionBold->setChecked(f.bold());
    ui->actionItalic->setChecked(f.italic());
    ui->actionUnderline->setChecked(f.underline());
    this->fontComboBox->setCurrentIndex(fontComboBox->findText(f.family()));
    QString size = QVariant(f.pointSizeF()).toString();
    int ind = this->fontSizeComboBox->findText(size);
    this->fontSizeComboBox->setCurrentIndex(ind);
}

void MainWindow::setTextFamily(const QString &f)
{
    if (this->prevCurTextEdit)
    {
	this->curTextEdit = this->prevCurTextEdit;
	this->prevCurTextEdit->setFontFamily(f);
    }
}

void MainWindow::setTextSize(const QString &p)
{
    if (this->prevCurTextEdit)
    {
	this->curTextEdit = this->prevCurTextEdit;
	this->prevCurTextEdit->setFontPointSize(p.toFloat());
    }
}

void MainWindow::on_actionBold_triggered()
{
    if (this->curTextEdit)
    {
	this->curTextEdit->setFontWeight(this->boldBtn->isChecked() ? QFont::Bold : QFont::Normal);
    }
}

void MainWindow::enabledInterface()
{
    this->grpAlign->setEnabled(true);
    this->grpFormating->setEnabled(true);
    this->grpPrint->setEnabled(true);

    ui->paginationAction->setEnabled(true);
    ui->actionAddQuestion->setEnabled(true);
    ui->actionAddImage->setEnabled(true);
}

void MainWindow::on_openAction_triggered()
{
    if (this->openFile())
    {
	this->grpPrint->setEnabled(true);
	ui->paginationAction->setEnabled(true);
    }
}

void MainWindow::on_actionItalic_triggered()
{
    if (this->curTextEdit)
    {
        this->curTextEdit->setFontItalic(this->italicBtn->isChecked());
    }
}

void MainWindow::on_actionUnderline_triggered()
{
    if (this->curTextEdit)
    {
        this->curTextEdit->setFontUnderline(this->underBtn->isChecked());
    }
}

void MainWindow::on_aboutMenu_triggered()
{
    if (!this->aboutDlg) this->aboutDlg = new CAboutDialog(this);
    this->aboutDlg->exec();
}

void MainWindow::on_actionAddQuestion_triggered()
{
    if (this->saveQuestBtn->isEnabled())
    {
	QString text = tr("Сохранить текущий вопрос перед добавлением нового вопроса?");
	int r = this->mbContinue(text);
	switch(r)
	{
	case QMessageBox::Cancel:
	    return;
	case QMessageBox::No:
	    this->ui->actionSaveQuestion->setEnabled(false);
	    break;
	case QMessageBox::Yes:
	    this->ui->actionSaveQuestion->setEnabled(false);
	    this->saveItem();
	    break;
	}
    }
    if(!testModel->insertRow(testModel->rowCount()))
    {
	QMessageBox box(this);
	box.setWindowTitle( tr("Test2Print") );
	box.setText( tr("Ошибка при добавлении вопроса.") );
	box.setIcon( QMessageBox::Critical );
	box.exec();
	return;
    }
    //Отображаем созданный вопрос
    selectionModel->clearSelection();
    selectionModel->setCurrentIndex(testModel->index(testModel->rowCount()-1, 0), QItemSelectionModel::SelectCurrent);
    if (appSettingsDlg)
	for (int i=0; i<appSettingsDlg->getDefaultAnswersCount(); i++)
	    on_actionAddAnswer_triggered();
    this->saveItem();
    ui->actionDelAnswer->setEnabled(false);
}

void MainWindow::on_actionDelQuestion_triggered()
{
    QModelIndexList list = selectionModel->selection().indexes();

    if (list.count() == 1)
    {
	QModelIndex index = list[0];
	selectionModel->clearSelection();

	if (index.row() < testModel->rowCount()-1)
	{
	    testModel->removeRow(index.row());
	    selectionModel->setCurrentIndex(testModel->index(index.row(), 0), QItemSelectionModel::SelectCurrent);
	}
	else
	{
	    selectionModel->setCurrentIndex(testModel->index(index.row()-1, 0), QItemSelectionModel::SelectCurrent);
	    testModel->removeRow(index.row());
	}
	ui->saveAction->setEnabled(true);
	ui->saveAsAction->setEnabled(true);
	if (testModel->rowCount()<=0)
		ui->actionDelQuestion->setEnabled(false);
    }
}

void MainWindow::on_actionAddAnswer_triggered()
{
    CAnswerForm *answerForm = new CAnswerForm;
    answerList.append(answerForm);
    testsVbl->insertWidget(answerList.count()-1, answerForm);
    connect(answerList.last(), SIGNAL(rightAnswerChecked()), this, SLOT(rightAnswerChecked()));
    connect(answerList.last(), SIGNAL(answerChanged()), this, SLOT(answerChanged()));
    connect(answerList.last(), SIGNAL(answerClicked(CAnswerForm*)), this, SLOT(answerClicked(CAnswerForm*)));
    countAddAnswer++;
    this->saveItem();
}

void MainWindow::on_actionDelAnswer_triggered()
{
    QModelIndex index;
    int n = answerList.indexOf(this->curAnswerForm);
    index = selectionModel->selectedIndexes().at(0);
    testModel->removeColumns(n*ANSWCOLUMN+3,ANSWCOLUMN,index);
    answerList.remove(answerList.indexOf(this->curAnswerForm));
    delete this->curAnswerForm;
    ui->saveAction->setEnabled(true);
    ui->saveAsAction->setEnabled(true);
    ui->actionSaveQuestion->setEnabled(true);
    if (answerList.isEmpty())
    {
	ui->actionDelAnswer->setEnabled(false);
	return;
    }
    if (n<answerList.count())
    {
	answerList.at(n)->activate();
	return;
    }
    if(n == answerList.count())
    {
	answerList.at(n-1)->activate();
    }
}

void MainWindow::on_actionSaveQuestion_triggered()
{
    if (selectionModel->selectedIndexes().isEmpty()) //если ничего не выделено
    {
	    ui->actionDelQuestion->setEnabled(false);
	return;
    }
    //Создаем индекс на основе выделенного пользователем элемента listView
    QModelIndex *index = new QModelIndex;
    *index = selectionModel->selectedIndexes().at(0);
    //проверка валидности itemа
    int row;
    if(index->isValid())
    {
	row = index->row();
	if(row >= testModel->rowCount())
	    return;
    }
    else
	row = selectionModel->selection().indexes()[0].row();

    if (this->countAddAnswer > 0)
	emit this->answerAdded(row, countAddAnswer);

    //сохраняем все в модель
    if(testModel->setData(testModel->index(row, 1,*index), ui->questTextEdit->toHtml()))
    {
	testModel->setData(testModel->index(row, 2, *index), ui->commentTextEdit->toHtml());
	for (int i=0; i<answerList.count(); i++)
	{
	    testModel->setData(testModel->index(row, i*ANSWCOLUMN+3, *index), answerList.at(i)->getAnswer());
	    testModel->setData(testModel->index(row, i*ANSWCOLUMN+4, *index), answerList.at(i)->isRightAnswer());

	}
	ui->actionSaveQuestion->setEnabled(false);
    }
    else
    {
	QMessageBox box(this);
	box.setWindowTitle( tr("Test2Print") );
	box.setText(tr("Ошибка сохранения"));
	box.setIcon( QMessageBox::Critical );
	box.exec();

    }
    countAddAnswer=0;
}

void MainWindow::on_newAction_triggered()
{
    if (ui->saveAction->isEnabled())
    {
	QString text = tr("Сохранить изменения и создать новый файл?");
	int r = mbContinue(text);
	switch (r)
	{
	case QMessageBox::Cancel:
	    return;
	    break;
	case QMessageBox::Yes:
	    this->saveFile();
	    break;
	}
    }
    testModel = new CTestModel();
    t2pFile = "";
    //очистка интерфейса
    this->deleteAnswerForms();
    ui->questTextEdit->clear();
    ui->commentTextEdit->clear();
    this->ui->actionSaveQuestion->setEnabled(false);
    QString title = tr("Test2Print - ") + t2pFile;
    if (!ui->centralWidget->isVisible()) ui->centralWidget->setVisible(true);

    this->setTitle(title);
    enabledInterface();
    this->initModel();
}

void MainWindow::on_saveAction_triggered()
{
    saveFile();
}

void MainWindow::on_printTestAction_triggered()
{
    CPrintTest *print = 0;
    print = new CPrintTest(this);
    CPrintSettings ps;
    if (this->paginationForm)
    {
	CPagination p = this->paginationForm->getPaginationSetting();
	ps.setPagination(p);
    }
    else
    {
	CPagination p = this->testModel->getPrintSettings().getPagination();
	ps.setPagination(p);
    }

    if (this->pageSetupDlg)
    {
	pageSettings = static_cast<CPageSettings*>(pageSetupDlg->printer());
	ps.setPageSettings(pageSettings);
    }
    else
    {
	pageSettings = this->testModel->getPrintSettings().getPageSettings();
	ps.setPageSettings(pageSettings);
    }

    print->printTest(testModel->getTest(), ps);
    if (print) delete print;
}

void MainWindow::on_actionPreview_triggered()
{
    CPrintTest *print = 0;
    print = new CPrintTest(this);
    CPrintSettings ps;
    CPagination p;

    if (this->pageSetupDlg)
    {
        pageSettings = static_cast<CPageSettings*>(pageSetupDlg->printer());
	ps.setPageSettings(pageSettings);
    }
    else
    {
        pageSettings = this->testModel->getPrintSettings().getPageSettings();
	ps.setPageSettings(pageSettings);
    }

    if (this->paginationForm)
    {
	p = this->paginationForm->getPaginationSetting();
        ps.setPagination(p);
    }
    else
    {
	p = this->testModel->getPrintSettings().getPagination();
        ps.setPagination(p);
    }

    print->printPreviewTest(testModel->getTest(), ps);
    if (print) delete print;
}

//Установка параметров страницы
void MainWindow::on_actionPageSetup_triggered()
{
    CPrintSettings ps;

    //Проверяем был ли открыт ранее диалог
    //если был берем из него параметры страницы, иначе берем параметры старницы из файла
    //и создаем диалог на основе этих параметров.
    if (this->pageSetupDlg)
    {
	pageSettings = static_cast<CPageSettings*>(pageSetupDlg->printer());
    }
    else
    {
	pageSettings = this->testModel->getPrintSettings().getPageSettings();
	pageSetupDlg = new QPageSetupDialog(pageSettings, this);
    }

    //Открываем диалог
    //Если пользователь нажал ОК, сохраняем параметры страницы в файл
    if (pageSetupDlg->exec() == QDialog::Accepted)
    {
	pageSettings = static_cast<CPageSettings*>(pageSetupDlg->printer());
	ps = this->testModel->getPrintSettings();
	ps.setPageSettings(pageSettings);
	this->testModel->savePrintSettings(ps);
	ui->saveAction->setEnabled(true);
	ui->saveAsAction->setEnabled(true);
    }
}

void MainWindow::on_paginationAction_triggered()
{
    if (!this->paginationForm)
    {
	this->paginationForm = new CPaginationForm(this->testModel->getPrintSettings().getPagination(), this);
	this->paginationForm->setModal(true);
    }

    if (this->paginationForm->exec() == QDialog::Accepted)
    {
	CPrintSettings ps;
	ps = this->testModel->getPrintSettings();
	CPagination p = this->paginationForm->getPaginationSetting();
	ps.setPagination(p);
	testModel->savePrintSettings(ps);
	ui->saveAction->setEnabled(true);
	ui->saveAsAction->setEnabled(true);
    }
}

void MainWindow::on_actionAppSettings_triggered()
{
    if (appSettingsDlg->exec() == QDialog::Accepted)
    {
	saveSettings();
    }
}

void MainWindow::saveSettings()
{
    if (appSettingsDlg)
    {
	QSettings settings("Test2Print", "Test2Print");
	settings.setValue("defaultAnswersCount", QVariant(appSettingsDlg->getDefaultAnswersCount()));
    }
}

void MainWindow::on_actionFontColor_triggered()
{
    QColor col = QColorDialog::getColor(this->curTextEdit->textColor(), this);
    if (!col.isValid())
	return;
    QTextCharFormat fmt;
    fmt.setForeground(col);
    mergeFormatOnWordOrSelection(fmt);
    colorChanged(col);
}

void MainWindow::colorChanged(const QColor &c)
{
    QPixmap pix(16, 16);
    pix.fill(c);
    ui->actionFontColor->setIcon(pix);
}

void MainWindow::mergeFormatOnWordOrSelection(const QTextCharFormat &format)
{
    QTextCursor cursor = this->curTextEdit->textCursor();
    if (!cursor.hasSelection())
	cursor.select(QTextCursor::WordUnderCursor);
    cursor.mergeCharFormat(format);
    this->curTextEdit->mergeCurrentCharFormat(format);
}

void MainWindow::dblClickOnTextEdit(CTextEdit *textEdit)
{
    QTextImageFormat image;
    image = textEdit->textCursor().charFormat().toImageFormat();
    if (image.isValid())
    {
	qDebug()<<textEdit->toHtml();
	CImageEditor *imageEditor = new CImageEditor();
	imageEditor->SetFormat(image);
	if (imageEditor->exec() == QDialog::Accepted)
	{
	    textEdit->refresh();
	}
	delete imageEditor;
	qDebug()<<textEdit->toHtml();
    }
}

void MainWindow::on_actionAddImage_triggered()
{
    QString fileimg = QFileDialog::getOpenFileName( this, tr("Вставить изображение"), "" ,tr("Image Files supported (*)"));

    if ( fileimg.isEmpty() )
    {
	return;
    }

    QImage base(fileimg);
    if (base.isNull() || !imageExtension(fileimg) )
    {
	QMessageBox::warning(this, tr("Ошибка загрузки изображения"),tr("Установите необходимый плагин или выберете другое изображение..\nДля вставки этого изображения откройте его в своем любимом графическом редакторе\nи пересохраните это изображение в одни из поддерживаемых форматов (png, jpg, gif)."));
	return;
    }

    if (imageExtension(fileimg))
    {
	if (this->curTextEdit)
	{
	    fileimg = testModel->addImage(fileimg);
	    if (!fileimg.isEmpty())
	    {
		QString subtext = QString("<img src=\"%1\" />").arg(fileimg);
		QTextDocumentFragment fragment = QTextDocumentFragment::fromHtml(subtext);
		this->curTextEdit->textCursor().insertFragment(fragment);
	    }
	}
	else
	    QMessageBox::warning(this, tr("Ошибка загрузки изображения"),tr("Для загрузки изображения установите курсор в неоходимое место."));
    }
}
